import asyncio
import websockets
import json
import logging
import sys
import data_struct

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
    stream=sys.stdout  # 确保输出到标准输出
)


async def handle_websocket(websocket):
    """处理WebSocket连接"""
    client_address = websocket.remote_address
    logging.info(f"WebSocket客户端已连接: {client_address}")
    
    try:
        # 发送欢迎消息
        await websocket.send(json.dumps({
            "type": "system",
            "message": "连接成功"
        }))
        
        async for message in websocket:
            try:
                # 验证数据格式
                data = json.loads(message)
                if 'type' in data and 'x' in data and 'y' in data:
                    joystick_type = data['type']
                    x = data['x']
                    y = data['y']
                    logging.info(f"收到{joystick_type}摇杆数据: X={x:.2f}, Y={y:.2f}")
                    if  joystick_type=="left":
                        data_struct.left_x = x
                        data_struct.left_y = y
                    else:
                        data_struct.right_x = x
                        data_struct.right_y = y
                    data_struct.print_method()
                    # 发送确认消息
                    await websocket.send(json.dumps({
                        "type": "ack",
                        "message": "数据已接收"
                    }))
            except json.JSONDecodeError:
                logging.error(f"无效的数据格式: {message}")
                await websocket.send(json.dumps({
                    "type": "error",
                    "message": "无效的数据格式"
                }))
    except websockets.exceptions.ConnectionClosed as e:
        logging.info(f"WebSocket连接已关闭: {client_address}, 代码: {e.code}, 原因: {e.reason}")
    except Exception as e:
        logging.error(f"处理WebSocket消息时出错: {str(e)}")
        try:
            await websocket.send(json.dumps({
                "type": "error",
                "message": f"服务器错误: {str(e)}"
            }))
        except:
            pass

async def main():
    """启动WebSocket服务器"""
    try:
        logging.info("正在启动WebSocket服务器...")
        async with websockets.serve(
            handle_websocket,
            '0.0.0.0',  # 监听所有网络接口
            9090,       # 端口
            ping_interval=20,  # 20秒发送一次ping
            ping_timeout=10    # 10秒没有响应就断开
        ) as server:
            logging.info("WebSocket服务器启动成功，监听端口: 9090")
            logging.info("等待客户端连接...")
            await asyncio.Future()  # 保持服务器运行
    except Exception as e:
        logging.error(f"启动WebSocket服务器时出错: {str(e)}")
        raise  # 重新抛出异常，让启动脚本知道服务器启动失败

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        logging.info("服务器被用户中断")
    except Exception as e:
        logging.error(f"服务器运行时出错: {str(e)}")
        sys.exit(1)  # 非零退出码表示错误 